package me.zhengjie.modules.supplier_app.rest;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.service.PictureService;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("app/supplier")
public class TAppSupplierPictureController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Autowired
    private PictureService pictureService;

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @Log("app上传图片")
    @PostMapping(value = "/pictures")
    @ResponseBody
    public ResponseEntity upload(HttpServletRequest request, @RequestParam MultipartFile file){
        String userName = SecurityUtils.getUsername();
        String picture = pictureService.upload(file);
        Map map = new HashMap();
        map.put("errno",0);
        //map.put("id",picture.getId());
        map.put("data",new String[]{picture});
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @Log("app查询图片")
    @GetMapping(value = "/picture/{uid:.+}")
    public void getPic(@PathVariable String uid,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + uid);
        File file;
        FileInputStream fileIn = null;
        ServletOutputStream out = null;
        try {
            String filePath = uploadFolder+"/" + uid;
            file = new File(filePath);
            fileIn = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] outputByte = new byte[1024];
            int readTmp = 0;
            while ((readTmp = fileIn.read(outputByte)) != -1) {
                out.write(outputByte, 0, readTmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileIn.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
